<?php
require 'config.php';

$id = (int)($_GET['id'] ?? 0);
/* 读原数据 */
$stmt = $pdo->prepare("SELECT * FROM notes WHERE id = ?");
$stmt->execute([$id]);
$note = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$note) {
    exit('<script>alert("记录不存在");location="index.php"</script>');
}

/* 提交保存 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sql = "UPDATE notes SET title = ?, content = ?, author = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['title'], $_POST['content'], $_POST['author'] ?: '匿名', $id]);
    header('Location: index.php');
    exit;
}
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>编辑记录 - 开源粘贴板</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="assets/ztb.png">
  <link rel="stylesheet" href="assets/bootstrap.min.css">
  <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="container-fluid">
  <div class="row">
    <!-- 侧边栏 -->
    <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
      <div class="text-center py-3"><h5 class="text-white">开源粘贴板</h5></div>
      <ul class="nav flex-column px-2">
        <li class="nav-item"><a class="nav-link" href="index.php">📋 全部记录</a></li>
        <li class="nav-item"><a class="nav-link" href="add.php">✍️ 写新记录</a></li>
        <li class="nav-item"><a class="nav-link active" href="#">✏️ 编辑记录</a></li>
      </ul>
    </nav>

    <!-- 主内容 -->
    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">编辑记录</h1>
        <a href="index.php" class="btn btn-secondary btn-sm">返回列表</a>
      </div>

      <div class="card">
        <div class="card-body">
          <form method="post">
            <div class="mb-3">
              <label class="form-label">标题</label>
              <input type="text" class="form-control" name="title" value="<?=htmlspecialchars($note['title'])?>" required>
            </div>
            <div class="mb-3">
              <label class="form-label">内容</label>
              <textarea class="form-control" name="content" rows="6" required><?=htmlspecialchars($note['content'])?></textarea>
            </div>
            <div class="mb-3">
              <label class="form-label">署名</label>
              <input type="text" class="form-control" name="author" value="<?=htmlspecialchars($note['author'])?>">
            </div>
            <button type="submit" class="btn btn-primary">保存修改</button>
          </form>
        </div>
      </div>
    </main>
  </div>
</div>
<script src="assets/bootstrap.bundle.min.js"></script>
</body>
</html>